# -*- coding: utf-8 -*-
import ast
import json
import math

import requests
from PyQt5.QtGui import QPixmap, QBrush, QColor, QFont
from PyQt5.QtWidgets import QWidget, QMessageBox, QLabel, QHeaderView, QVBoxLayout, QTableWidgetItem, QAbstractItemView, \
    QGraphicsScene, QGraphicsPixmapItem, QLineEdit, QComboBox, QDateEdit, QFileDialog, QHBoxLayout, QPushButton
from PyQt5.QtCore import Qt, QRect, pyqtSignal, QDir

from ImageUploaderThread import ImageUploaderThread
from aysncImageLoader import AsyncImageLoader
from ui import detail
import constant
from utils import api


class DetailWindow(QWidget, detail.Ui_form):
    imgCol = 3

    def __init__(self, token=None, id=0, clickedFun=None):
        super().__init__()
        self.setupUi(self)
        self.token = token
        self.graphicsView.hide()
        self.setWindowTitle(constant.APP_NAME)
        self.uploadSuccess = []
        self.clickedFun = clickedFun

        font = QFont()
        font.setFamily("宋体")
        font.setPixelSize(10)
        self.tableWidget.setFont(font)
        print('clickedFun: ' + clickedFun)
        print("detail window: " + str(id))

        if clickedFun == 'btn_zufangDetail_click':
            self.setWindowTitle(constant.APP_NAME + '-房屋详情')
            self.getFangDetail(id, 'zufang')
        elif clickedFun == 'btn_shoufangDetail_click':
            self.setWindowTitle(constant.APP_NAME + '-房屋详情')
            self.getFangDetail(id, 'shoufang')
        elif clickedFun == 'btn_areaDetail_click':
            self.setWindowTitle(constant.APP_NAME + '-小区详情')
            self.getAreaDetail(id)

    def getFangDetail(self, id, kind):
        try:
            url = constant.API_HOST + '/detail'
            data = {
                'id': id,
                'kind': kind
            }
            res = api.get(self, url, data)
            if res is not None and res['code'] == 0:
                tableWidget = self.tableWidget
                tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                tableWidget.setRowCount(4)
                tableWidget.setColumnCount(6)
                tableWidget.setWordWrap(True)

                for i in range(len(tableWidget.horizontalHeader())):
                    if i % 2 == 0:
                        tableWidget.horizontalHeader().setSectionResizeMode(i, QHeaderView.ResizeToContents)

                brush = QBrush(QColor(150, 150, 150))
                tableWidget.setItem(0, 0, QTableWidgetItem('小区名称：'))
                tableWidget.setItem(0, 1, QTableWidgetItem(res['data']['area_name']))
                tableWidget.item(0, 1).setForeground(brush)
                tableWidget.setItem(0, 2, QTableWidgetItem('户型：'))
                tableWidget.setItem(0, 3, QTableWidgetItem(str(res['data']['house_type'])))
                tableWidget.item(0, 3).setForeground(brush)
                tableWidget.setItem(0, 4, QTableWidgetItem('带看次数：'))
                tableWidget.setItem(0, 5, QTableWidgetItem(str(res['data']['look_times'])))
                tableWidget.item(0, 5).setForeground(brush)
                tableWidget.setItem(1, 0, QTableWidgetItem('发布日期：'))
                tableWidget.setItem(1, 1, QTableWidgetItem(res['data']['publish_at']))
                tableWidget.item(1, 1).setForeground(brush)
                tableWidget.setItem(1, 2, QTableWidgetItem('联系方式：'))
                tableWidget.setItem(1, 3, QTableWidgetItem(str(res['data']['phone'])))
                tableWidget.item(1, 3).setForeground(brush)
                tableWidget.setItem(1, 4, QTableWidgetItem('意向人数：'))
                tableWidget.setItem(1, 5, QTableWidgetItem(str(res['data']['like_customer'])))
                tableWidget.item(1, 5).setForeground(brush)
                tableWidget.setItem(2, 0, QTableWidgetItem('标题：'))
                tableWidget.setSpan(2, 1, 1, 3)
                tableWidget.setItem(2, 1, QTableWidgetItem(str(res['data']['title'])))
                tableWidget.item(2, 1).setForeground(brush)
                tableWidget.setItem(2, 4, QTableWidgetItem('更新时间：'))
                tableWidget.setItem(2, 5, QTableWidgetItem(str(res['data']['updated_at'])))
                tableWidget.item(2, 5).setForeground(brush)
                tableWidget.setItem(3, 0, QTableWidgetItem('备注：'))
                tableWidget.setSpan(3, 1, 1, 5)
                tableWidget.setItem(3, 1, QTableWidgetItem(str(res['data']['remark'])))
                tableWidget.item(3, 1).setForeground(brush)
                tableWidget.item(3, 1).setTextAlignment(Qt.AlignLeading)
                tableWidget.resizeRowsToContents()

                self.images = ast.literal_eval(res['data']['house_images'])
                if self.images is not None:
                    rowNum = math.ceil(len(self.images) / self.imgCol)
                    tableWidget2 = self.tableWidget_2
                    tableWidget2.setColumnCount(self.imgCol)
                    tableWidget2.setRowCount(rowNum)
                    tableWidget2.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                    tableWidget2.verticalHeader().setDefaultSectionSize(150)

                    AsyncImageLoader(self.images, self.display_image)


        except requests.exceptions.ConnectionError:
            QMessageBox().about(self, '提示', '服务器连接失败')

    def getAreaDetail(self, id):
        try:
            url = constant.API_HOST + '/setting/area_detail'
            data = {
                'id': id,
            }
            res = api.get(self, url, data)
            if res is not None and res['code'] == 0:
                tableWidget = self.tableWidget
                tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                tableWidget.setRowCount(3)
                tableWidget.setColumnCount(6)
                tableWidget.setWordWrap(True)

                for i in range(len(tableWidget.horizontalHeader())):
                    if i % 2 == 0:
                        tableWidget.horizontalHeader().setSectionResizeMode(i, QHeaderView.ResizeToContents)

                brush = QBrush(QColor(150, 150, 150))
                tableWidget.setItem(0, 0, QTableWidgetItem('小区名称：'))
                tableWidget.setItem(0, 1, QTableWidgetItem(res['data']['area_name']))
                tableWidget.item(0, 1).setForeground(brush)
                tableWidget.setItem(0, 2, QTableWidgetItem('物业类型：'))
                tableWidget.setItem(0, 3, QTableWidgetItem(str(res['data']['area_type'])))
                tableWidget.item(0, 3).setForeground(brush)
                tableWidget.setItem(0, 4, QTableWidgetItem('竣工时间：'))
                tableWidget.setItem(0, 5, QTableWidgetItem(str(res['data']['finish_time'])))
                tableWidget.item(0, 5).setForeground(brush)
                tableWidget.setItem(1, 0, QTableWidgetItem('产权年限：'))
                tableWidget.setItem(1, 1, QTableWidgetItem(res['data']['limit_year']))
                tableWidget.item(1, 1).setForeground(brush)
                tableWidget.setItem(1, 2, QTableWidgetItem('建筑类型：'))
                tableWidget.setItem(1, 3, QTableWidgetItem(str(res['data']['build_type'])))
                tableWidget.item(1, 3).setForeground(brush)
                tableWidget.setItem(1, 4, QTableWidgetItem('开发商：'))
                tableWidget.setItem(1, 5, QTableWidgetItem(str(res['data']['area_builder'])))
                tableWidget.item(1, 5).setForeground(brush)
                tableWidget.setItem(2, 0, QTableWidgetItem('小区地址：'))
                tableWidget.setSpan(2, 1, 1, 5)
                tableWidget.setItem(2, 1, QTableWidgetItem(str(res['data']['area_address'])))
                tableWidget.item(2, 1).setForeground(brush)
                tableWidget.resizeRowsToContents()

                self.images = ast.literal_eval(res['data']['area_images'])
                if self.images is not None:
                    rowNum = math.ceil(len(self.images) / self.imgCol)
                    tableWidget2 = self.tableWidget_2
                    tableWidget2.setColumnCount(self.imgCol)
                    tableWidget2.setRowCount(rowNum)
                    tableWidget2.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                    tableWidget2.verticalHeader().setDefaultSectionSize(150)

                    AsyncImageLoader(self.images, self.display_image)


        except requests.exceptions.ConnectionError:
            QMessageBox().about(self, '提示', '服务器连接失败')

    def click_image(self, pixmap):
        scene = QGraphicsScene()
        pixmap_item = QGraphicsPixmapItem(pixmap)
        scene.addItem(pixmap_item)

        self.graphicsView.raise_()
        self.graphicsView.setScene(scene)
        self.graphicsView.mousePressEvent = lambda _: self.click_graphicsView()
        self.graphicsView.show()

    def click_graphicsView(self):
        self.graphicsView.setScene(None)
        self.graphicsView.hide()

    finished = pyqtSignal(str)  # 发送上传是否成功的信号

    def upload_images(self, uploadType):
        # 选择图片文件
        files, _ = QFileDialog.getOpenFileNames(self, "Select Images", QDir.homePath(), "Images (*.jpg *.png)")
        if files:
            for file in files:
                self.uploadThread = ImageUploaderThread(file, uploadType)
                self.uploadThread.finished.connect(self.on_upload_finished)  # 假设有一个处理上传结果的槽函数
                self.uploadThread.start()

    def on_upload_finished(self, res):
        json_dict = json.loads(res)
        print(json_dict)
        if json_dict['code'] == 0:
            print(json_dict['data'])
            print("Image uploaded successfully!")
            self.uploadSuccess.append(json_dict['data']['path'])

            self.images = self.uploadSuccess
            rowNum = math.ceil(len(self.images) / self.imgCol)
            tableWidget2 = self.tableWidget_2
            tableWidget2.setColumnCount(self.imgCol)
            tableWidget2.setRowCount(rowNum)
            tableWidget2.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            tableWidget2.verticalHeader().setDefaultSectionSize(150)

            AsyncImageLoader(self.uploadSuccess, self.display_image)

        else:
            QMessageBox().about(self, '提示', '图片上传失败：' + json_dict['message'])
            print(json_dict['message'])
            print("Error uploading image!")

    def display_image(self, image, i):
        label = QLabel()
        pixmap = QPixmap.fromImage(image)
        label.setPixmap(pixmap)
        label.setScaledContents(True)
        label.mousePressEvent = lambda _, pixmap=pixmap: self.click_image(pixmap)
        row = math.floor(i / self.imgCol)
        col = i % self.imgCol

        self.tableWidget_2.setCellWidget(row, col, label)
        print(f"Image from {i} loaded successfully")
